<template>
  <carrier :title="title">
    <div slot="top">
      <!-- 警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
    </div>
    <div slot="count">
      <!-- 选择商品分类 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectKey"
            :options="sortList"
            :props="{
              value: 'cat_id',
              label: 'cat_name',
              expandTrigger: 'hover',
              children: 'children',
            }"
            clearable
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页标签 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数选项 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="disableBtn"
            @click="addSortDialogVisible = true"
            >添加参数
          </el-button>
          <el-table :data="manyTabData" style="width: 100%" border>
            <el-table-column type="expand" width="60px">
              <template slot-scope="scope">
                 <el-tag v-for="item,i in scope.row.attr_vals" :key="i" closable v-show="item" @close="handleClose(scope.row, item)">
                   {{item}}
                 </el-tag>
                 <el-input v-if="scope.row.input_visible" v-model="scope.row.input_val" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                 <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column label="参数名称" prop="attr_name"> </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleEditClick(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性选项 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="disableBtn"
            @click="addSortDialogVisible = true"
            >添加属性
          </el-button>
          <el-table :data="onlyTabData" style="width: 100%" border>
            <el-table-column type="expand" width="60px">
              <template slot-scope="scope">
                 <el-tag v-for="item,i in scope.row.attr_vals" :key="i" closable v-show="item">
                   {{item}}
                 </el-tag>
                 <el-input v-if="scope.row.input_visible" v-model="scope.row.input_val" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                 <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope"> 
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleEditClick(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数/属性对话框 -->
      <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addSortDialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <el-form
          ref="dialogForm"
          :model="addForm"
          :rules="addFormRule"
          :status-icon="true"
        >
          <el-form-item :label="titleText" label-width="90px" prop="attr_name">
            <el-input v-model="addForm.attr_name" @keyup.enter.native="addParams"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="addSortDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑参数/属性对话框 -->
      <el-dialog
        :title="'编辑' + titleText"
        :visible.sync="editSortDialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <el-form
          ref="dialogForm"
          :model="editForm"
          :status-icon="true"
        >
          <el-form-item :label="titleText" label-width="90px" prop="attr_name">
            <el-input v-model="editForm.attr_name" @keyup.enter.native="handleEdit"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editSortDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEdit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </carrier>
</template>

<script>
import Carrier from "views/home/Carrier.vue";

import { getHomeData, getHomeData2 } from "network/home.js";

export default {
  name: "Params",
  data() {
    return {
      title: ["商品管理", "分类参数"],
      selectKey: "",
      sortList: [],
      activeName: "many",
      editSortDialogVisible: false,
      onlyTabData: [],
      manyTabData: [],
      addSortDialogVisible: false,
      addForm: {
        attr_name: "",
      },
      addFormRule: {
        attr_name: [
          { required: true, message: `请添加相应参数`, trigger: "blur" },
        ],
      },
      editForm: {
        attr_name: ''
      }
    };
  },
  components: {
    Carrier,
  },
  created() {
    this.getSortData();
  },
  methods: {
    // 获取所有分类的数据
    getSortData() {
      getHomeData({
        url: "categories",
        params: {
          type: 3,
        },
      }).then((res) => {
        if (res.meta.status !== 200)
          return this.$message({
            type: "error",
            message: res.meta.msg,
          });
        this.sortList = res.data;
      });
    },
    // 选择器选中事件处理
    handleChange() {
      this.getParamsData();
    },
    // tag标签页点击处理
    handleClick() {
      this.getParamsData();
    },
    // 动态获取参数数据
    async getParamsData() {
      if (this.selectKey.length === 0) return;

      try {
        let val = await getHomeData({
          url: `categories/${this.selectKey[2]}/attributes`,
          params: {
            sel: this.activeName,
          }
        })
        // console.log(val);
        let res = JSON.parse(JSON.stringify(val))
        if (res.meta.status !== 200) throw res
        res.data.forEach(v => {
          v.attr_vals = v.attr_vals?.split(',') ?? []
          v.input_val = ''
          v.input_visible = false
        } )
        // console.log(res.data);
        if (this.activeName === "only") {
          this.onlyTabData = res.data;
        } else {
          this.manyTabData = res.data;
        }
      } catch (err) {
        this.$message({
            type: "error",
            message: err.meta.msg
          });
      }
    },
    addDialogClose() {
      this.$refs.dialogForm.resetFields();
    },
    addParams() {
      getHomeData(
        {
          url: `categories/${this.selectKey[2]}/attributes`,
          data: {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          },
        },
        "post"
      ).then((res) => {

        this.addSortDialogVisible = false

        if (res.meta.status !== 201)
          return this.$message({
            type: "error",
            message: res.meta.msg,
          });
        this.getParamsData();
      });
    },
    async handleInputConfirm(val) {
      // console.log(val);
      if(!val.input_visible) return
      val.input_visible = false
      if(!val.input_val) return
      val.attr_vals.push(val.input_val)
      
      // console.log(val);
      let {attr_name, attr_sel, attr_vals} = val
      let str = attr_vals.join(',')
      // console.log(str);
      try {
        let res = await getHomeData({
          url: `categories/${this.selectKey[2]}/attributes/${val.attr_id}`,
          data: {
            attr_name,
            attr_sel,
            attr_vals: str
          }
        }, 'put')
        // console.log(res);
        if(res.meta.status != 200) throw 'err'
      } catch (error) {
        this.$message.error('更新失败')
      }
    },
    showInput(val) {
      val.input_visible = true
      val.input_val = ''
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除标签
     async handleClose(data, val) {
      // console.log(data);
      data.attr_vals.splice(data.attr_vals.indexOf(val), 1)
      try {
        let {attr_name, attr_sel, attr_vals} = data

        let res = await getHomeData({
          url: `categories/${this.selectKey[2]}/attributes/${data.attr_id}`,
          data: {
            attr_name,
            attr_sel,
            attr_vals: attr_vals.join(',')
          }
        }, 'put')
        // console.log(res);
        if(res.meta.status !== 200) throw 'err'
      } catch (error) {
        this.$message.error('更新失败')
      }
    },
    handleEditClick(val) {
      // console.log(val);
      this.editSortDialogVisible = true
      this.editForm.attr_name = val.attr_name
      this.editForm.attr_id = val.attr_id
    },
    // 编辑属性 / 参数
    async handleEdit() {
      let {attr_name, attr_id} = this.editForm
      try {
        let res = await getHomeData({
          url: `categories/${this.selectKey[2]}/attributes/${attr_id}`,
          data: {
            attr_name,
            attr_sel: this.activeName
          }
        }, 'put')
        if(res.meta.status != 200) throw 'err'
        this.$message.success('更新成功')
        this.getParamsData();
        // console.log(res);
      } catch (error) {
        this.$message.error('编辑失败')
      }
    },
    // 删除属性 / 参数
    async handleDel(val) {
      // console.log(val);
      try {
        await this.$confirm('此操作将永久删除该分类, 是否继续?', '注意', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await getHomeData({
          url: `categories/${this.selectKey[2]}/attributes/${val.attr_id}`
        }, 'delete')
        if(res.meta.status != 200) throw 'err'
        this.$message.success('删除成功')
        this.getParamsData();
      } catch (error) {
        if(error == 'cancel') return this.$message.info('已取消删除')
        this.$message.error('删除失败')
      }
    }
  },
  computed: {
    // 动态计算是否禁用按钮
    disableBtn() {
      if (this.selectKey.length === 0) return true;
      return false;
    },
    // 动态计算对话框标题文本
    titleText() {
      if (this.activeName === "only") {
        return "静态属性";
      }
      return "动态参数";
    },
  },
};
</script>

<style scoped>
.el-row {
  margin-bottom: 15px;
}
.el-button {
  margin: 5px;
}
.el-cascader {
  width: 30%;
}
.el-input--small{
  width: 200px;
  margin: 10px 0;
}
.el-tag {
  margin-right: 15px;
}
.el-table {
  max-height: 60vh;
}
</style>